package com.yao.club.service.impl;

import com.netease.yidun.sdk.core.utils.StringUtils;
import com.yao.club.entity.UserEntity;
import com.yao.club.entity.dto.InformationDetail;
import com.yao.club.entity.result.ResponseEntity;
import com.yao.club.entity.dto.InformationType;
import com.yao.club.entity.dto.SysImg;
import com.yao.club.entity.result.ResultEntity;
import com.yao.club.entity.vo.InformationDetailVO;
import com.yao.club.mapper.UserMapper;
import com.yao.club.reposittory.InformationDetailRepository;
import com.yao.club.reposittory.InformationTypeRepository;
import com.yao.club.reposittory.SysImageRepository;
import com.yao.club.service.InformationService;
import com.yao.club.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class InformationServiceImpl implements InformationService {

    @Autowired
    private InformationTypeRepository informationTypeRepository;

    @Resource
    UserMapper userMapper;

    @Autowired
    SysImageRepository imageRepository;
    @Autowired
    private InformationDetailRepository informationDetailRepository;

    @Override
    public ResponseEntity<List<InformationType>> getInformationTypes() {
        try {
            // 获取所有启用的资讯类型
            List<InformationType> types = informationTypeRepository.findAllEnabled();
            return ResponseUtils.success(types);
        } catch (Exception e) {
            return ResponseUtils.failed("获取资讯类型列表失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseEntity<ResultEntity<InformationDetailVO>> getInformationList(String typeId, String keyword, Integer pageNum, Integer pageSize) {
        try {
            ResultEntity result = new ResultEntity<InformationDetailVO>();

            // 创建分页请求
            Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
            List<InformationDetailVO> records = new ArrayList<>();
            // 查询指定类型的资讯
           // 查询资讯
           Page<InformationDetail> page;
            
           if (StringUtils.isNotEmpty(typeId) && StringUtils.isNotEmpty(keyword)) {
               // 同时按类型和关键字搜索
               page = informationDetailRepository.findByTypeIdAndKeyword(typeId, keyword, pageable);
           } else if (StringUtils.isNotEmpty(typeId)) {
               // 只按类型搜索
               page = informationDetailRepository.findByInformationTypeIdOrderByCreateTimeDesc(typeId, pageable);
           } else if (StringUtils.isNotEmpty(keyword)) {
               // 只按关键字搜索
               page = informationDetailRepository.findByKeyword(keyword, pageable);
           } else {
               // 获取所有有效资讯
               page = informationDetailRepository.findAll(pageable);
           }

            //设置结果
            for (InformationDetail information : page.getContent()) {
                InformationDetailVO detailVO = new InformationDetailVO();
                BeanUtils.copyProperties(information, detailVO);
                //图片处理
                if (information.getImgIds() != null && !information.getImgIds().isEmpty()) {
                    String[] ids = information.getImgIds().split(",");
                    List<SysImg> images = new ArrayList<>();
                    for (String id : ids) {
                        images.add(imageRepository.selectById(id));
                    }
                    detailVO.setImages(images);

                }
                //处理头像
                if (StringUtils.isNotEmpty(information.getCreateBy())) {
                    UserEntity userEntity = userMapper.getUserByMemberId(information.getCreateBy());
                    SysImg userImg = imageRepository.selectById(userEntity.avatar_id + "");
                    detailVO.setAvatar(userImg);
                }
                records.add(detailVO);
            }

            // 设置分页结果
            result.setRecords(records);
            result.setTotal((int) page.getTotalElements());
            result.setSize(pageSize);
            result.setCurrent(pageNum);
            result.setPages(page.getTotalPages());

            return ResponseUtils.success(result);
        } catch (Exception e) {
            return ResponseUtils.failed("获取资讯列表失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseEntity<InformationDetailVO> getInformationDetail(String id) {
        try {
            // 获取资讯信息
            Optional<InformationDetail> informationOpt = informationDetailRepository.findById(id);
            if (!informationOpt.isPresent()) {
                return ResponseUtils.failed("资讯不存在");
            }

            InformationDetail information = informationOpt.get();
            if (information.getDelFlag() != 0) {
                return ResponseUtils.failed("资讯已下架");
            }

            // 转换为VO对象
            InformationDetailVO detailVO = new InformationDetailVO();
            BeanUtils.copyProperties(information, detailVO);
            //图片处理
            if (information.getImgIds() != null && !information.getImgIds().isEmpty()) {
                String[] ids = information.getImgIds().split(",");
                List<SysImg> images = new ArrayList<>();
                for (String id_ : ids) {
                    images.add(imageRepository.selectById(id_));
                }
                detailVO.setImages(images);

            }
            //处理头像
            if (StringUtils.isNotEmpty(information.getCreateBy())) {
                UserEntity userEntity = userMapper.getUserByMemberId(information.getCreateBy());
                SysImg userImg = imageRepository.selectById(userEntity.avatar_id + "");
                detailVO.setAvatar(userImg);
            }
            // 获取资讯类型信息
            Optional<InformationType> typeOpt = informationTypeRepository.findById(information.getInformationTypeId());
            typeOpt.ifPresent(type -> detailVO.setInformationTypeName(type.getName()));

            return ResponseUtils.success(detailVO);
        } catch (Exception e) {
            return ResponseUtils.failed("获取资讯详情失败：" + e.getMessage());
        }
    }
}
